// 进程监控API客户端
class ProcessAPI {
    constructor() {
        this.baseURL = '/api/processes';
    }

    // 获取所有进程连接 - 对应 GET /api/processes/connections
    async getProcessConnections() {
        try {
            const response = await fetch(`${this.baseURL}/connections`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const result = await response.json();
            return result.success ? result.data : [];
        } catch (error) {
            console.error('获取进程连接失败:', error);
            throw error;
        }
    }

    // 获取指定进程统计 - 对应 GET /api/processes/:pid
    async getProcessStats(pid) {
        try {
            const response = await fetch(`${this.baseURL}/${pid}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const result = await response.json();
            return result.success ? result.data : null;
        } catch (error) {
            console.error(`获取进程${pid}统计失败:`, error);
            throw error;
        }
    }

    // 获取所有进程统计 - 对应 GET /api/processes
    async getAllProcessStats() {
        try {
            const response = await fetch(this.baseURL);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const result = await response.json();
            return result.success ? result.data : { processes: [], summary: {}, count: 0 };
        } catch (error) {
            console.error('获取所有进程统计失败:', error);
            throw error;
        }
    }

    // 获取进程速度统计 - 对应 GET /api/processes/speed
    async getProcessSpeedStats() {
        try {
            const response = await fetch(`${this.baseURL}/speed`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const result = await response.json();
            return result.success ? result.data : [];
        } catch (error) {
            console.error('获取进程速度统计失败:', error);
            throw error;
        }
    }

    // 过滤进程连接
    filterConnections(connections, filters) {
        const {
            showListening = true,
            showEstablished = true,
            processFilter = '',
            portFilter = ''
        } = filters;

        return connections.filter(conn => {
            // 状态过滤
            if (!showListening && conn.status === 'LISTEN') return false;
            if (!showEstablished && conn.status === 'ESTABLISHED') return false;

            // 进程名过滤
            if (processFilter && !conn.process_name.toLowerCase().includes(processFilter.toLowerCase())) {
                return false;
            }

            // 端口过滤
            if (portFilter) {
                const port = parseInt(portFilter);
                if (isNaN(port)) return false;
                if (conn.local_port !== port && conn.remote_port !== port) return false;
            }

            return true;
        });
    }

    // 过滤进程列表
    filterProcesses(processes, searchQuery) {
        if (!searchQuery) return processes;
        
        const query = searchQuery.toLowerCase();
        return processes.filter(process => {
            return process.process_name.toLowerCase().includes(query) ||
                   process.pid.toString().includes(query) ||
                   (process.username && process.username.toLowerCase().includes(query)) ||
                   (process.executable && process.executable.toLowerCase().includes(query));
        });
    }

    // 构建连接状态CSS类
    getConnectionStatusClass(status) {
        const statusMap = {
            'ESTABLISHED': 'established',
            'LISTEN': 'listening',
            'TIME_WAIT': 'timewait',
            'CLOSE_WAIT': 'closewait',
            'SYN_SENT': 'synsent',
            'SYN_RECV': 'synrecv',
            'FIN_WAIT1': 'finwait1',
            'FIN_WAIT2': 'finwait2',
            'CLOSING': 'closing',
            'LAST_ACK': 'lastack',
            'UNCONN': 'unconn'
        };
        return statusMap[status] || 'unknown';
    }

    // 构建协议CSS类
    getProtocolClass(protocol) {
        return protocol.toLowerCase();
    }

    // 计算进程汇总统计
    calculateSummary(processes) {
        return {
            totalProcesses: processes.length,
            activeProcesses: processes.filter(p => p.is_alive).length,
            totalConnections: processes.reduce((sum, p) => sum + (p.total_connections || 0), 0),
            totalTCPConns: processes.reduce((sum, p) => sum + (p.active_tcp || 0), 0),
            totalUDPConns: processes.reduce((sum, p) => sum + (p.active_udp || 0), 0),
            totalTrafficDown: processes.reduce((sum, p) => sum + (p.total_recv || 0), 0),
            totalTrafficUp: processes.reduce((sum, p) => sum + (p.total_sent || 0), 0)
        };
    }

    // 格式化进程数据（使用后端返回的格式化字符串）
    formatProcessData(processes) {
        return processes.map(process => ({
            ...process,
            // 使用后端提供的格式化字符串
            displayTotalSent: process.total_sent_text || '0 B',
            displayTotalRecv: process.total_recv_text || '0 B',
            displayStartTime: process.start_time || 'N/A',
            displayLastUpdate: process.last_update || 'N/A'
        }));
    }

    // 格式化连接数据（使用后端返回的格式化字符串）
    formatConnectionData(connections) {
        return connections.map(conn => ({
            ...conn,
            // 使用后端提供的格式化字符串
            displayBytesSent: conn.bytes_sent_text || '0 B',
            displayBytesRecv: conn.bytes_recv_text || '0 B',
            displayCreatedAt: conn.created_at || 'N/A',
            displayLastSeen: conn.last_seen || 'N/A'
        }));
    }

    // 错误处理
    handleError(error, context = '进程API') {
        console.error(`${context}错误:`, error);
        
        if (error.name === 'TypeError' && error.message.includes('fetch')) {
            return '网络连接失败，请检查服务器状态';
        } else if (error.message.includes('404')) {
            return '进程不存在或API接口未找到';
        } else if (error.message.includes('500')) {
            return '服务器内部错误';
        } else {
            return error.message || '未知错误';
        }
    }
}

// 创建全局实例
window.processAPI = new ProcessAPI();